var urlObj = {
    avatarUrl: "",
    enclosureUrl: "",
    enclosureName: "",
    avatarName: ""
}

$(function () {
    //初始化隐藏组件
    if (!$('#enclosure').hasOwnProperty('href')) {
        $('#enclosure').hide();
        $('#avatarImage').hide();
    }
    $('#submit').click(function () {
        registration = getInputValues(urlObj);
        console.log(registration);
        ajax.createTable(registration, function (result) {
            if (result.status == 0) {
                window.location.href = '/'
            }
        })
    })

    //给img标签添加点击事件
    $("#avatarImage").click(function () {
        $("#avatarImage").hide();
        $("#avatarUrl").show();
        urlObj.avatarUrl = "";
        urlObj.avatarName = "";
    })
})

function uploadEnclosure() {
    var formData = new FormData();
    if ($('#file')[0].files[0] == null || undefined) {
        return;
    }
    formData.append('file', $('#file')[0].files[0]);
    $.ajax({
        url: '/upload/enclosure',
        type: "POST",
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        dataType: 'json',
        success: function (result) {
            if (result == null || undefined) {
                return;
            }
            console.log(result.fileName);
            console.log(result.filePath);
            urlObj.enclosureUrl = result.filePath + result.fileName;
            urlObj.enclosureName = result.fileName;
            showEnclosureUrl(urlObj.enclosureUrl, urlObj.enclosureName);

        },
        error: function (result) {
        }
    });
}


function showEnclosureUrl(enclosureUrl, enclosureName) {
    $('#file').hide();
    $('#enclosure').show();
    $('#enclosure').attr('href', enclosureUrl)
    $('#enclosure').attr('download', enclosureName);
    $('#enclosure').text(enclosureName);
}

function uploadAvatarUrl() {
    var formData = new FormData();
    if ($('#avatarUrl')[0].files[0] == null || undefined) {
        return;
    }
    formData.append('file', $('#avatarUrl')[0].files[0]);
    $.ajax({
        url: '/upload/avatarUrl',
        type: "POST",
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        dataType: 'json',
        success: function (result) {
            if (result == null || undefined) {
                return;
            }
            console.log(result.fileName);
            console.log(result.filePath);
            urlObj.avatarUrl = result.filePath + result.fileName;
            urlObj.avatarName = result.fileName;
            showAvatarUrl(urlObj.avatarUrl, urlObj.avatarUrl);

        },
        error: function (result) {
        }
    });
}

function showAvatarUrl(avatarUrl) {
    $('#avatarUrl').hide();
    $('#avatarImage').show();
    $('#avatarImage').attr('src', avatarUrl)
}


